package com.flute.haflute.agent.heartbeat;

import java.io.IOException;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.haflute.common.ClusterConstants.ROLE;
import com.flute.haflute.net.messaging.Message;
import com.flute.haflute.net.messaging.Message.MessageType;
import com.flute.haflute.net.messaging.MessageFactory;
import com.flute.haflute.tools.Utils;

/**
 * BDM的心跳发送处理器
 */
public class BDMHeartBeatSender extends IoHandlerAdapter implements
		HeartBeatSender {

	private static Logger logger = LoggerFactory
			.getLogger(BDMHeartBeatSender.class);

	private boolean successful = false;

	/*
	 * @see com.flute.haflute.agent.HeartBeatSender#sendHeartBeat()
	 */
	@Override
	public void sendHeartBeat(IoSession session2DM) {
		successful = false;
		try {
			Message message = MessageFactory.getHeartBeatMessage();
			message.setHeader("role", ROLE.BDM.name().getBytes());
			Utils.sendMessage(session2DM, message);
		} catch (IOException e) {
			logger.error("", e);
		}
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		Message realMessage = (Message) message;
		if (realMessage.getMessageType().equals(MessageType.HBACK.name())) {
			Utils.sendMessage(session, MessageFactory.getHeartBeatAck2Message());
			successful = true;
			logger.debug("send one heartbeat to DM successfully");
		}
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
	}

	/*
	 * @see com.flute.haflute.agent.heartbeat.HeartBeatSender#isSuccessful()
	 */
	@Override
	public boolean isSuccessful() {
		return successful;
	}

}
